package com.rc.saas.tenant.controller.shop;

import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadImg;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.shop.ShopGoods;
import com.rc.saas.tenant.model.shop.ShopGoodsClass;
import com.rc.saas.tenant.model.shop.ShopGoodsExample;
import com.rc.saas.tenant.model.shop.ShopGoodsImage;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.ticket.TenantTicketType;
import com.rc.saas.tenant.search.shop.ShopGoodSearch;
import com.rc.saas.tenant.search.shop.ShopStockRecordSearch;
import com.rc.saas.tenant.service.shop.*;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.ticket.TenantTicketTypeService;
import com.rc.saas.tenant.upyun.WebUploader;
import com.rc.saas.tenant.vo.shop.ShopGoodsVo;
import com.rc.saas.tenant.vo.shop.ShopOrderHistoryVo;
import com.rc.saas.tenant.vo.shop.ShopStockRecordVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/shopGoods")
public class ShopGoodsController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(ShopGoodsController.class);

    @Autowired
    private ShopGoodsService shopGoodsService;

    @Autowired
    private ShopGoodsClassService shopGoodsClassService;

    @Autowired
    private ShopOrderService shopOrderService;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private UploadImg uploadImg;

    @Autowired
    private ShopGoodsImageService shopGoodsImageService;

    @Autowired
    private ShopStockRecordService shopStockRecordService;

    @Autowired
    private TenantTicketTypeService tenantTicketTypeService;


    /**
     * 跳转商品管理
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String shopOrderInfoPage(Model model) {
        try {
            TenantUser user = getSessionTenantUser();
            Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());
            model.addAttribute("uploadPath", upYunConfig.getDownloadRoot());
            model.addAttribute("shopVerificationCode", tenant.getShopVerificationCode());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "/templates/shopGoods/shopOrder";
    }

    /**
     * 分页查询数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageShopGood", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listShopOrder(ShopGoodSearch shopGoodSearch) {
        PageInfo<ShopGoodsVo> pageInfo = shopGoodsService.listPageByCondition(shopGoodSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 增/改 商品属性(上架下架，完善退货信息，新增录入商品数据)
     */
    @RequestMapping(value = "/saveOrUpdateShopOrder", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateShopOrder(ShopGoodsVo shopGoodsVo,
                                           @RequestParam(value = "imageOriginal_file", required = false) MultipartFile imageOriginal,
                                           @RequestParam(value = "imageDetail1_file", required = false) MultipartFile imageDetail1,
                                           @RequestParam(value = "imageDetail2_file", required = false) MultipartFile imageDetail2,
                                           @RequestParam(value = "imageDetail3_file", required = false) MultipartFile imageDetail3,
                                           @RequestParam(value = "imageBroadcast1_file", required = false) MultipartFile imageBroadcast1,
                                           @RequestParam(value = "imageBroadcast2_file", required = false) MultipartFile imageBroadcast2,
                                           @RequestParam(value = "imageBroadcast3_file", required = false) MultipartFile imageBroadcast3,
                                           @RequestParam(value = "imageBroadcast4_file", required = false) MultipartFile imageBroadcast4,
                                           @RequestParam(value = "imageBroadcast5_file", required = false) MultipartFile imageBroadcast5,
                                           @RequestParam(value = "goodsImage_file", required = false) MultipartFile goodsImage) {
        TenantUser user = getSessionTenantUser();
        try {
            if (imageOriginal != null && imageOriginal.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), imageOriginal);
                if (tResponse.getStatus() == 200) {
                    shopGoodsVo.setImageOriginal((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (imageDetail1 != null && imageDetail1.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), imageDetail1);
                if (tResponse.getStatus() == 200) {
                    shopGoodsVo.setImageDetail1((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (imageDetail2 != null && imageDetail2.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), imageDetail2);
                if (tResponse.getStatus() == 200) {
                    shopGoodsVo.setImageDetail2((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (imageDetail3 != null && imageDetail3.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), imageDetail3);
                if (tResponse.getStatus() == 200) {
                    shopGoodsVo.setImageDetail3((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (goodsImage != null && goodsImage.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), goodsImage);
                if (tResponse.getStatus() == 200) {
                    shopGoodsVo.setGoodsImage((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (imageBroadcast1 != null && imageBroadcast1.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), imageBroadcast1);
                if (tResponse.getStatus() == 200) {
                    shopGoodsVo.setImageBroadcast1((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (imageBroadcast2 != null && imageBroadcast2.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), imageBroadcast2);
                if (tResponse.getStatus() == 200) {
                    shopGoodsVo.setImageBroadcast2((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (imageBroadcast3 != null && imageBroadcast3.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), imageBroadcast3);
                if (tResponse.getStatus() == 200) {
                    shopGoodsVo.setImageBroadcast3((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (imageBroadcast4 != null && imageBroadcast4.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), imageBroadcast4);
                if (tResponse.getStatus() == 200) {
                    shopGoodsVo.setImageBroadcast4((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (imageBroadcast5 != null && imageBroadcast5.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), imageBroadcast5);
                if (tResponse.getStatus() == 200) {
                    shopGoodsVo.setImageBroadcast5((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }

        } catch (Exception e) {
            return TResponse.FAIL("图片上传失败");
        }


        shopGoodsVo.setTenantCode(user.getTenantCode());
        shopGoodsVo.setLastUpdatedTime(new Date());
        return shopGoodsService.saveOrUpdateShopOrder(shopGoodsVo);
    }

    /**
     * 查看商品
     */
    @RequestMapping(value = "/selectShopGoods", method = RequestMethod.GET)
    @ResponseBody
    public Object selectShopGoods(Model model, Long goodsId) {
        try {
            HashMap<String, Object> map = new HashMap<>();
            TenantUser user = getSessionTenantUser();
            ShopGoods shopGoods = shopGoodsService.selectByPrimaryKey(goodsId);
            ShopGoodsImage shopGoodsImage = shopGoodsImageService.selectByPrimaryKey(goodsId);
            List<ShopGoodsClass> shopGoodsClassList = shopGoodsClassService.listByTenantCode(user.getTenantCode());
            if (shopGoodsClassList.size() == 0) {
                //数据初始化
                shopGoodsClassService.initData(user.getTenantCode());
                //重新查询
                shopGoodsClassList = shopGoodsClassService.listByTenantCode(user.getTenantCode());
            }
            if (shopGoods.getTicketTypeId() != null) {
                TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(shopGoods.getTicketTypeId());
                map.put("tenantTicketType", tenantTicketType);
            }
            map.put("shopGoodsClassList", shopGoodsClassList);
            map.put("shopGoods", shopGoods);
            map.put("shopGoodsImage", shopGoodsImage);
            map.put("uploadPath", upYunConfig.getDownloadRoot());

            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 补货减货功能
     * type 0补货，1减货
     */
    @RequestMapping(value = "/addOrReduceShopGoods", method = RequestMethod.GET)
    @ResponseBody
    public TResponse addOrReduceShopGoods(int type, int num, Long goodsId, String remark) {
        try {
            Pattern pattern = Pattern.compile("[0-9]*");
            if (!pattern.matcher(String.valueOf(num)).matches()) {
                return TResponse.FAIL("参数应为正整数");
            }
            ShopGoods shopGoods = shopGoodsService.selectByPrimaryKey(goodsId);
            if (shopGoods != null && type == 1) {
                if (shopGoods.getStockNum() - num < 0) {
                    return TResponse.FAIL("减货后不能小于0");
                }
            }
            shopGoodsService.addOrReduceShopGoods(shopGoods, type, remark, num);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return TResponse.FAIL();
        }
    }


    /**
     * 库存明细
     * 通过goodsId指定商品id
     */
    @RequestMapping(value = "/listPageHistory", method = RequestMethod.GET)
    @ResponseBody
    public Object listPageHistory(Model model, ShopStockRecordSearch shopStockRecordSearch) {
        try {
            PageInfo<ShopStockRecordVo> pageInfo = shopStockRecordService.listPageByConditionWithHistory(shopStockRecordSearch);
            WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
            return webPageInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 商品核销码刷新
     */
    @RequestMapping(value = "/updateShopVerificationCode", method = RequestMethod.GET)
    @ResponseBody
    public TResponse updateShopVerificationCode() {
        try {
            TenantUser user = getSessionTenantUser();
            Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());
            tenant.setShopVerificationCode(new Random().nextInt(9000) + 1000 + "");
            tenantService.updateByPrimaryKey(tenant);
            return TResponse.SUCCESS(tenant.getShopVerificationCode());
        } catch (Exception e) {
            e.printStackTrace();
            return TResponse.FAIL();
        }
    }


    /**
     * ShopGoods图片删除通用接口
     * goods;
     */
    @RequestMapping(value = "/deleteImage", method = RequestMethod.GET)
    @ResponseBody
    public TResponse deleteImage(ShopGoodsVo shopGoodsVo) {
        if (shopGoodsVo.getGoodsId() == null) {
            return TResponse.FAIL("商品参数缺失");
        }
        WebUploader webUploader = WebUploader.getInstance(upYunConfig);
        return shopGoodsService.deleteImages(webUploader, shopGoodsVo);
    }

    /**
     * 查询优惠券是否在商品中使用
     */
    @RequestMapping(value = "/selectByTicketTypeId", method = RequestMethod.GET)
    @ResponseBody
    public TResponse selectByTicketTypeId(Long ticketTypeId) {
        try {
            if (ticketTypeId != null) {
                List<ShopGoods> list = shopGoodsService.listByTicketTypeId(ticketTypeId);
                if (list != null && list.size() > 0) {
                    return TResponse.SUCCESS();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return TResponse.FAIL();
        }

        return TResponse.FAIL();
    }


}
